<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="流程标识" prop="processKey">
        <el-input
          v-model="queryParams.processKey"
          placeholder="请输入流程标识"
          clearable
        />
      </el-form-item>
      <el-form-item label="流程名称" prop="processName">
        <el-input
          v-model="queryParams.processName"
          placeholder="请输入流程名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="流程分类" prop="category">
        <el-select
          v-model="queryParams.category"
          clearable
          placeholder="请选择流程分类"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- v-hasPermi="['workflow:process:startExport']" -->
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table v-loading="loading" fit :data="processList">
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <el-table-column
        label="流程标识"
        prop="processKey"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="流程名称" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-button text @click="handleProcessView(scope.row)">
            <span>{{ scope.row.processName }}</span>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="流程分类"
        prop="categoryName"
        :formatter="categoryFormat"
      />
      <el-table-column label="流程版本">
        <template #default="scope">
          <el-tag size="small">v{{ scope.row.version }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag type="success" v-if="!scope.row.suspended">激活</el-tag>
          <el-tag type="warning" v-if="scope.row.suspended">挂起</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="部署时间" prop="deploymentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deploymentTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- v-hasPermi="['workflow:process:start']" -->
          <el-button
            type="primary"
            text
            icon="el-icon-video-play"
            @click="
              islinkPerson ? handleStart(scope.row) : userInputFocus(scope.row)
            "
            >发起</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 流程图 -->
    <el-dialog
      :title="processView.title"
      v-model:visible="processView.open"
      width="70%"
      append-to-body
    >
      <my-process-viewer
        key="designer"
        :value="processView.xmlData"
        v-bind="bpmnControlForm"
        :prefix="bpmnControlForm.prefix"
        :activityData="activityList"
        :processInstanceData="processInstance"
        :taskData="tasks"
      />
    </el-dialog>
    <!-- 弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="closeFn"
    ></SelectDialog>
  </div>
</template>

<script name="WorkProcess" setup>
import { useRoute, useRouter } from 'vue-router'
import { listProcess, getBpmnXml, startProcess } from '@/api/workflow/process'
import { listAllCategory } from '@/api/workflow/category'
import { getPricipalId } from '@/utils/commo'
import myProcessViewer from '@/components/bpmnProcessDesigner/package/designer/ProcessViewer.vue'
import { toRefs } from 'vue'
const router = useRouter()
const { proxy } = getCurrentInstance()
const attrs = useAttrs()
const props = defineProps({
  paramsObj: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
const data = reactive({
  // 遮罩层
  loading: true,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    processKey: undefined,
    processName: undefined,
    category: undefined
  },
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  filterCategoryText: '',
  categoryOptions: [],
  categoryProps: {
    label: 'categoryName',
    value: 'code'
  },
  // 流程定义表格数据
  processList: [],
  processView: {
    title: '',
    open: false,
    index: undefined,
    xmlData: ''
  },
  dialogParam: {}
})
const {
  // 遮罩层
  loading,
  // 查询参数
  queryParams,
  // 显示搜索条件
  showSearch,
  // 总条数
  total,
  filterCategoryText,
  categoryOptions,
  categoryProps,
  // 流程定义表格数据
  processList,
  processView,
  dialogParam
} = toRefs(data)
const islinkPerson = ref(true) //是否存在下一环节人
const rowObj = ref({}) //行数据
/** 查询流程分类列表 */
function getCategoryList() {
  listAllCategory().then(response => (categoryOptions.value = response.data))
}
/** 查询流程定义列表 */
function getList() {
  loading.value = true
  listProcess(queryParams.value).then(response => {
    processList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
// 重置按钮操作
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    processKey: undefined,
    processName: undefined,
    category: undefined
  }
  handleQuery()
}
// ========== 高亮流程图 start ==========
const bpmnControlForm = ref({
  prefix: 'flowable'
})
const activityList = ref([])
const processInstance = ref({})
const tasks = ref([])
/** 查看流程图 */
const handleProcessView = row => {
  let modelId = row.modelId
  processView.value.title = '流程图'
  processView.value.index = modelId
  // 发送请求，获取xml
  getBpmnXml(modelId).then(response => {
    processView.value.xmlData = response.data
  })
  processView.value.open = true
}
// ========== 高亮流程图 end ==========
/**发起 */
function handleStart(row) {
  console.log(row, '参数---')
  let prams = {
    businessId: props.paramsObj.businessId, //业务id
    linkPersonId: linkPerson.value.linkPersonId //下一环节人
  }
  startProcess(row.definitionId, prams).then(res => {
    proxy.$modal.msgSuccess('发起成功')
    //调爷组件的ProjectDetails 的方法
    attrs.onInitiate('contractStatus')
  })
}
/** 导出按钮操作 */
function handleExport() {
  proxy.downLoadByUrl(
    'bpmn/workflow/process/startExport',
    {
      ...queryParams.value
    },
    `wf_start_process_${new Date().getTime()}.xlsx`
  )
}
function categoryFormat(row, column) {
  return (
    categoryOptions.value.find(k => k.code === row.category)?.categoryName ?? ''
  )
}
/**** 下一环节人 模块 start */
const linkPerson = ref({})
/**
 * 获取焦点事件
 */
function userInputFocus(row) {
  rowObj.value = row
  dialogParam.value = {
    type: 'principalId',
    title: '请选择下一环节人',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: false,
    checkStrictly: false
  }
  dialogParam.value.isDialog = true
  dialogParam.value.defaultCheckedKeys = []
}
/** 弹出框下拉框
 * 项目负责人
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  switch (val.type) {
    case 'principalId':
      linkPerson.value['principalId'] = val.selectData
      linkPerson.value.principal = val.labelData.toString()
      linkPerson.value.principalId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      linkPerson.value.linkPersonId = val.selectData
        ? getPricipalId(val.selectData, val.defaultCheckedKeys)
        : ''
      handleStart(rowObj.value)
      break
  }
}
/**
 * 弹出框关闭
 * @param {*} val
 */
const closeFn = val => {
  dialogParam.value.isDialog = false
}
/**** 项目负责人 模块 end */
getCategoryList()
getList()
</script>
